<?php
/**
 * Created by PhpStorm.
 * User: huynguyen
 * Date: 3/19/14
 * Time: 9:11 PM
 */

class ProductController extends Controller{
    /**
     * Declares class-based actions.
     */
    public function actions()
    {
        return array(

            // page action renders "static" pages stored under 'protected/views/site/pages'
            // They can be accessed via: index.php?r=site/page&view=FileName
            'page' => array(
                'class' => 'CViewAction',
            ),
        );
    }


    /**
     * This is the default 'index' action that is invoked
     * when an action is not explicitly requested by users.
     */
    public function actionIndex($catSlug =null, $prodSlug = null)
    {
        $criteria= new CDbCriteria;
        $criteria->select = array('FN_QTC_MULTI_NAME(P.PRODUCT_NAME, P.PRODUCT_ENG_NAME, :LANG_CODE) AS PRODUCT_NAME'
        ,'FN_QTC_MULTI_NAME(P.SLUG, P.SLUG_ENG, :LANG_CODE) AS SLUG'
        , 'DETAIL'
        , 'KEYWORDS');
        $criteria->condition = " P.SLUG = :SLUG";
        //$criteria->order = " SORT_ORDER ";
        $criteria->params =  array(':LANG_CODE'=> Yii::app()->language, ':SLUG'=> $prodSlug);
        $criteria->alias =  "P";

        // select products
        $product = Product::model()->with(array("GroupFile","Menu" => array("select" => array("FN_QTC_MULTI_NAME(Menu.MENU_NAME, Menu.MENU_ENG_NAME, :LANG_CODE) AS MENU_NAME",
            "FN_QTC_MULTI_NAME(Menu.MENU_SLUG, Menu.MENU_SLUG_ENG, :LANG_CODE) AS SLUG"))) )->find($criteria);

        //select categories
        $criteria->select = array(  'T2.MENU_CODE',
            'T2.PARENT_MENU_CODE',
            'FN_QTC_MULTI_NAME(T2.MENU_NAME, T2.MENU_ENG_NAME, :LANG_CODE) AS MENU_NAME',
            'FN_QTC_MULTI_NAME(T2.MENU_SLUG, T2.MENU_SLUG_ENG, :LANG_CODE) AS MENU_SLUG');
        $criteria->condition = " T2.USE_YN = 'Y' ";
        $criteria->order = " T1.LVL DESC";
        $criteria->alias = "T2";
        $criteria->join = 'INNER JOIN ( SELECT @r AS _CODE,
                                                 (SELECT @r := PARENT_MENU_CODE FROM TB_QTC_MENU WHERE MENU_CODE = _CODE) AS PARENT_MENU_CODE,
                                                  @l := @l + 1 AS LVL
                                               FROM
                                                  (SELECT @r := MENU_CODE, @l := 0 FROM TB_QTC_MENU M WHERE (M.MENU_SLUG = :SLUG OR M.MENU_SLUG_ENG = :SLUG) AND USE_YN =\'Y\') vars,
                                                  TB_QTC_MENU M
                                             WHERE @r <> 0) T1 ON T1._CODE = T2.MENU_CODE';
        $criteria->params =  array(':LANG_CODE'=> Yii::app()->language, ':SLUG'=> $catSlug);
        $categories = Menu::model()->findAll($criteria);


        $this->render('index', array("categories"=> $categories, "product" => $product));
    }


} 